package Dao.DaoImpl;

import Utils.JDBCUtils;
import org.springframework.beans.factory.parsing.BeanEntry;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import Dao.UserDao;
import domain.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<User> findUserByUsername(String username) {
        String sql = "select * from user where username = ?";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class),username);
        return users;
    }

    @Override
    public void addUser(User user) {
        String sql = "insert into user values(null,?,?,?,?)";
        template.update(sql,user.getUsername(),user.getPassword(),user.getType(),user.getStunum());
    }

    @Override
    public void updateUser(User user) {
        String sql = "update user set username=?,type=?,stunum=? where id=?";
       template.update(sql,user.getUsername(),user.getType(),user.getStunum(),user.getId());
    }

    @Override
    public void deleteUser(String username) {
        String sql = "delete from user where username=?";
        template.update(sql,username);
    }

    @Override
    public List<User> fuzztSelectUser(HashMap<String, String> map) {
        String sql = "select * from user where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        Set<String> set = map.keySet();
        List<Object> params = new ArrayList<Object>();
        for (String key : set) {
            String value = map.get(key);

            //判断value是否有值
            if(value!=null && !"".equals(value)){
                //有值就拼接
                sb.append(" and "+key+" like ?");
                params.add("%"+value+"%");//上面 ?的值
            }
        }

        sql = sb.toString();

        return template.query(sql,new BeanPropertyRowMapper<User>(User.class),params.toArray());
    }

    @Override
    public List<User> userList() {
        String sql = "select * from user";
        return template.query(sql,new BeanPropertyRowMapper<User>(User.class));
    }



















}
